package com.fancy.learncenter.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonAnswerKeysBean;
import com.fancy.learncenter.bean.CartoonAnswersBean;
import com.fancy.learncenter.bean.CartoonCommitAnswerBean;
import com.fancy.learncenter.bean.CartoonFillBlankBean;
import com.fancy.learncenter.bean.CartoonGetAnswerResultBean;
import com.fancy.learncenter.bean.CartoonGetHomeAnswerBean;
import com.fancy.learncenter.bean.CartoonMediaBean;
import com.fancy.learncenter.bean.CartoonOptionsBean;
import com.fancy.learncenter.bean.CartoonQuestionBankBean;
import com.fancy.learncenter.bean.CartoonStemsBean;
import com.fancy.learncenter.bean.CartoonTextsBean;
import com.fancy.learncenter.bean.QuestionVOsBean;
import com.fancy.learncenter.common.JumpIntentKey;
import com.fancy.learncenter.common.MAudioPlayer;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.adapter.EnglishSentenceAdapter;
import com.fancy.learncenter.ui.view.CartoonAnalysisPopu;
import com.fancy.learncenter.ui.view.GridSpacingItemDecoration;
import com.fancy.learncenter.utils.CartoonToastUtils;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;
import com.zhy.view.flowlayout.TagView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;

import static com.fancy.learncenter.common.JumpIntentKey.OPTION_STATUS.STATUS_CHOOSE;
import static com.fancy.learncenter.common.JumpIntentKey.OPTION_STATUS.STATUS_DEFAULT;
import static com.fancy.learncenter.common.JumpIntentKey.OPTION_STATUS.STATUS_RIGHT;
import static com.fancy.learncenter.common.JumpIntentKey.OPTION_STATUS.STATUS_WORD;
import static com.fancy.learncenter.common.JumpIntentKey.OPTION_STATUS.STATUS_WRONG;
import static com.fancy.learncenter.common.JumpIntentKey.RIGHT_NUM;

/**
 * 语法题-----选词填空（1 文本 2 文本+图片 3 文本+音频）
 * <p>
 * <p>
 * 业务逻辑：空格 3种状态 未选中 选中 填充文字
 */
public class GrammarChooseFillBlankFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @Bind(R.id.commit_image)
    ImageView commitImage;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.xRefreshView)
    XRefreshView xRefreshView;

    TextView questionText;
    ImageView voiceImage;
    SimpleDraweeView questionImage;
    @Bind(R.id.previous_question)
    ImageView previousQuestion;
    @Bind(R.id.next_question)
    ImageView nextQuestion;
    @Bind(R.id.bottom_layout)
    RelativeLayout bottomLayout;
    // TODO: Rename and change types of parameters
    private int currentIndex;
    private int totalNum;
    TagFlowLayout flowLayout;
    private List<CartoonTextsBean> optionsTextList = new ArrayList<>();
    private OnGrammarChooseFillBlankListener mListener;
    private String questionStr;
    EnglishSentenceAdapter adapter;
    ArrayList<QuestionVOsBean> questionList;
    private boolean isCheck = false;
    int position;
    FillBlankAdapter fillBlankAdapter;
    List<CartoonFillBlankBean> blankList;

    private List<CartoonTextsBean> answersList = new ArrayList<>();
    private List<String> standardAnswerList = new ArrayList<>();
    private List<String> writeList = new ArrayList<>();
    private String titleStr;
    private JumpIntentKey.QUESTION_ENTER_TYPE type;
    private String homePackageId;
    private View invisibleView;
    private int state;
    private List<CartoonCommitAnswerBean> commitAnswerBeanList;
    private QuestionVOsBean questionVOsBean;
    private String studentHomeworkId;
    private Fragment currentFragment;
    private JumpIntentKey.CARTOON_BUTTON_STATUS buttonStatus;
    private List<CartoonFillBlankBean> importAnswerList = new ArrayList<>();
    private String analysisText;
    private List<String> writeAnswerIdList = new ArrayList<>();
    private String audioUrl;
    private MAudioPlayer audioPlayer;
    private String lessonNameStr;
    private String unitNameStr;

    public GrammarChooseFillBlankFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     */
    // TODO: Rename and change types and number of parameters
    public static GrammarChooseFillBlankFragment newInstance(ArrayList<QuestionVOsBean> list, int currentIndex, int totalNum, JumpIntentKey.QUESTION_ENTER_TYPE type,
                                                             String homePackageId, String studentHomeworkId, String lessonNameStr, String unitNameStr) {
        GrammarChooseFillBlankFragment fragment = new GrammarChooseFillBlankFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, currentIndex);
        args.putInt(ARG_PARAM2, totalNum);
        args.putSerializable(JumpIntentKey.QUESTION_ENTER, type);
        args.putParcelableArrayList(JumpIntentKey.QUSETION_BANK_LIST_KEY, list);
        args.putString(JumpIntentKey.HOMEWORK_PACKAGE_ID, homePackageId);
        args.putString(JumpIntentKey.STUDENTHOMEWORKID, studentHomeworkId);
        args.putString(JumpIntentKey.LESSON_NAME, lessonNameStr);
        args.putString(JumpIntentKey.UNIT_NAME, unitNameStr);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        currentFragment = this;
        if (getArguments() != null) {
            currentIndex = getArguments().getInt(ARG_PARAM1);
            totalNum = getArguments().getInt(ARG_PARAM2);
            type = (JumpIntentKey.QUESTION_ENTER_TYPE) getArguments().getSerializable(JumpIntentKey.QUESTION_ENTER);
            questionList = getArguments().getParcelableArrayList(JumpIntentKey.QUSETION_BANK_LIST_KEY);
            homePackageId = getArguments().getString(JumpIntentKey.HOMEWORK_PACKAGE_ID);
            studentHomeworkId = getArguments().getString(JumpIntentKey.STUDENTHOMEWORKID);
            lessonNameStr = getArguments().getString(JumpIntentKey.LESSON_NAME);
            unitNameStr = getArguments().getString(JumpIntentKey.UNIT_NAME);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_grammar_choose_fill_blank, container, false);
        ButterKnife.bind(this, view);
        initRecycleView();
        initData();
        initClick();
        return view;
    }

    private void initClick() {
        switch (type) {
            case DO_WORK:
            case CONTINUE_WORK:
                previousQuestion.setVisibility(View.GONE);
                nextQuestion.setVisibility(View.GONE);
                break;
            case DO_IT_AGAIN:
                previousQuestion.setVisibility(View.GONE);
                nextQuestion.setVisibility(View.GONE);
                break;
            case WORK_REPORT:
                previousQuestion.setVisibility(View.VISIBLE);
                nextQuestion.setVisibility(View.VISIBLE);
                if (currentIndex == 0) {
                    previousQuestion.setVisibility(View.GONE);
                }
                if (currentIndex == totalNum - 1) {
                    nextQuestion.setVisibility(View.GONE);
                }
                getWorkReportAnswer();
                break;
            case HAS_CORRECTED:
            case NOT_CORRECTED:
            case ERROR_KINDS:
                previousQuestion.setVisibility(View.VISIBLE);
                nextQuestion.setVisibility(View.VISIBLE);
                if (currentIndex == 0) {
                    previousQuestion.setVisibility(View.GONE);
                }
                if (currentIndex == totalNum - 1) {
                    nextQuestion.setVisibility(View.GONE);
                }

                break;
        }
        commitImage.setOnClickListener(this);
        commitImage.setEnabled(false);
        previousQuestion.setOnClickListener(this);
        nextQuestion.setOnClickListener(this);
        voiceImage.setOnClickListener(this);
    }

    private void initRecycleView() {

        xRefreshView.setPullRefreshEnable(false);

        View headView = getActivity().getLayoutInflater().inflate(R.layout.word_see_image_listen_spell_head_view, null);
        questionText = (TextView) headView.findViewById(R.id.question_name);
        questionImage = (SimpleDraweeView) headView.findViewById(R.id.question_image);
        voiceImage = (ImageView) headView.findViewById(R.id.voice_image);
        flowLayout = (TagFlowLayout) headView.findViewById(R.id.flowlayout);
        invisibleView = headView.findViewById(R.id.invisible_view);
        invisibleView.setVisibility(View.GONE);

        GridSpacingItemDecoration decoration = new GridSpacingItemDecoration(2, 40, true, true);
        adapter = new EnglishSentenceAdapter(getActivity(), optionsTextList, type);
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 2);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        recyclerView.addItemDecoration(decoration);
        recyclerView.setAdapter(adapter);
        adapter.setHeaderView(headView, recyclerView);
        adapter.setListener(new EnglishSentenceAdapter.ClickListener() {
            @Override
            public void click(CartoonTextsBean value, int position) {

                if (!isCheck) {
                    return;
                }

                for (int i = 0; i < blankList.size(); i++) {
                    if (blankList.get(i).getStatus().equals(STATUS_CHOOSE)) {
                        blankList.get(i).setId(String.valueOf(value.getId()));
                        blankList.get(i).setOptionValue(value.getValue());
                        blankList.get(i).setStatus(STATUS_WORD);
                        break;
                    }
                }


                fillBlankAdapter.notifyDataChanged();
                isShowCommit();
            }
        });

    }


    private void initData() {
        questionVOsBean = questionList.get(currentIndex);

        CartoonOptionsBean optionsBean = questionVOsBean.getOptions();
        CartoonStemsBean stemsBean = questionVOsBean.getStems();
        CartoonAnswersBean answersBean = questionVOsBean.getAnswers();
        titleStr = questionVOsBean.getConstructionNameCn();
        onButtonPressed(currentIndex + 1, totalNum, titleStr);
        if (answersBean != null) {
            answersList = answersBean.getTexts();
            for (CartoonTextsBean textsBean : answersList) {
                standardAnswerList.add(textsBean.getValue());
                CartoonFillBlankBean bean = new CartoonFillBlankBean();
                bean.setOptionValue(textsBean.getValue());
                bean.setId(String.valueOf(textsBean.getId()));
                importAnswerList.add(bean);
            }
        }

        CartoonAnswerKeysBean answerKeysBean = questionVOsBean.getAnswerKeys();
        if (answerKeysBean != null) {
            List<CartoonTextsBean> answerKeysList = answerKeysBean.getTexts();
            if (answerKeysList != null && answerKeysList.size() > 0) {

                analysisText = answerKeysList.get(0).getValue();
            }
        }

        if (optionsBean != null) {
            optionsTextList.addAll(optionsBean.getTexts());
            adapter.notifyDataSetChanged();
        }

        if (stemsBean != null) {
            List<CartoonMediaBean> audioList = stemsBean.getAudios();
            if (audioList != null && audioList.size() > 0) {
                audioUrl = audioList.get(0).getPlayLink();
                voiceImage.setVisibility(View.VISIBLE);
            } else {
                voiceImage.setVisibility(View.GONE);
            }

            List<CartoonMediaBean> imageList = stemsBean.getImages();
            if (imageList != null && imageList.size() > 0) {
                questionImage.setImageURI(imageList.get(0).getImgUrl());
                questionImage.setVisibility(View.VISIBLE);
            } else {
                questionImage.setVisibility(View.GONE);
            }

            questionStr = stemsBean.getTexts().get(0).getValue();
        }

        blankList = new ArrayList<>();
        String[] questionNameList = questionStr.split(" ");
        for (int i = 0; i < questionNameList.length; i++) {

            CartoonFillBlankBean blankBean = new CartoonFillBlankBean();
            blankBean.setStatus(STATUS_DEFAULT);
            blankBean.setValue(questionNameList[i]);
            CartoonFillBlankBean blankBean2 = new CartoonFillBlankBean();
            blankBean2.setStatus(STATUS_DEFAULT);
            blankBean2.setValue(" ");
//            blankBean.setValue(String.valueOf(questionStr.charAt(i)));
            blankList.add(blankBean);
            blankList.add(blankBean2);
        }

        fillBlankAdapter = new FillBlankAdapter(blankList);
        flowLayout.setAdapter(fillBlankAdapter);

        flowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {

                switch (type) {
                    case DO_WORK:
                    case CONTINUE_WORK:
                    case DO_IT_AGAIN:
                    case ERROR_KINDS:
                        break;
                    case WORK_REPORT:
                        return true;
                    case NO_CLICK:
                        return true;

                }

                isCheck = true;
                TagView tagView = (TagView) view;
                LinearLayout linearLayout = (LinearLayout) tagView.getTagView();
                switch (blankList.get(position).getStatus()) {
                    case STATUS_DEFAULT:
                        for (int i = 0; i < blankList.size(); i++) {

                            if (i != position && blankList.get(i).getStatus().equals(STATUS_CHOOSE)) {
                                blankList.get(i).setStatus(STATUS_DEFAULT);
                            }
                        }
                        blankList.get(position).setStatus(STATUS_CHOOSE);
                        break;
                    case STATUS_CHOOSE:
                        break;
                    case STATUS_WORD:
                        blankList.get(position).setStatus(STATUS_DEFAULT);
                        break;
                }


                adapter.notifyDataSetChanged();
                fillBlankAdapter.notifyDataChanged();


                return true;
            }
        });
    }


    /**
     * 获取客观题答案
     */
    private void getWorkReportAnswer() {

        Map<String, Object> map = new HashMap<>();
        map.put("packageId", homePackageId);
        map.put("classId", MyApplication.classIDStr);
        map.put("questionId", questionVOsBean.getQuestionId());

        HttpMehtod.getInstance().cartoonGetHomeAnswer(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                final BaseBean<CartoonGetAnswerResultBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonGetAnswerResultBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonGetAnswerResultBean>() {
                    @Override
                    public void success(CartoonGetAnswerResultBean dataBean) {

                        if (dataBean != null) {
                            CartoonGetHomeAnswerBean homeAnswerBean = dataBean.getResult();
                            List<CartoonCommitAnswerBean> answerResourceList = homeAnswerBean.getAnswerResourceList();
                            List<String> tempIdList = new ArrayList<>();
                            for (CartoonCommitAnswerBean bean : answerResourceList) {
                                tempIdList.add(bean.getQuestionResourceId());
                            }

                            List<String> tempStrList = new ArrayList<>();
                            List<CartoonFillBlankBean> blankBeanList = new ArrayList<>();
                            for (int i = 0; i < optionsTextList.size(); i++) {
                                if (tempIdList.size() > 0 && String.valueOf(optionsTextList.get(i).getId()).equals(tempIdList.get(0))) {
                                    CartoonFillBlankBean blankBean = new CartoonFillBlankBean();
                                    String value = optionsTextList.get(i).getValue();
                                    tempStrList.add(value);
                                    blankBean.setValue(value);
                                    blankBean.setId(String.valueOf(optionsTextList.get(i).getId()));
                                    blankBeanList.add(blankBean);

                                    optionsTextList.get(i).setHidden(1);
                                    tempIdList.remove(0);
                                }
                            }
                            if (Utils.compare(tempStrList, standardAnswerList)) {
                                commitImage.setVisibility(View.INVISIBLE);
                            } else {

                                buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_SEE_ANSWER;
                                Utils.notifyButtonBg(buttonStatus, commitImage);
                            }

                            List<String> tempAnswerList = new ArrayList<>();
                            tempAnswerList.addAll(standardAnswerList);
                            int index = 0; //标志顺序
                            for (int i = 0; i < blankList.size(); i++) {

                                if ("##".equals(blankList.get(i).getValue())) {
                                    if (blankBeanList != null && blankBeanList.size() > 0 && tempAnswerList != null && tempAnswerList.size() > 0) {
                                        if (blankBeanList.get(0).getValue().equals(tempAnswerList.get(0))) {
                                            blankList.get(i).setStatus(STATUS_RIGHT);
                                        } else {
                                            blankList.get(i).setStatus(STATUS_WRONG);
                                        }
                                        tempAnswerList.remove(0);
                                        blankList.get(i).setIndex(index);
                                        blankList.get(i).setId(blankBeanList.get(0).getId());
                                        blankList.get(i).setOptionValue(tempStrList.get(0));
                                        blankBeanList.remove(0);
                                        index++;
                                    }

                                }
                            }
                            adapter.notifyDataSetChanged();
                            fillBlankAdapter.notifyDataChanged();
                        }

                    }

                    @Override
                    public void fail(String errorCode) {


                    }
                }).dealData();
            }
        });

    }


    /**
     * 是否点亮提交按钮
     */
    private void isShowCommit() {
        writeList.clear();
        for (CartoonFillBlankBean textsBean : blankList) {
            if (!TextUtils.isEmpty(textsBean.getOptionValue())) {
                writeList.add(textsBean.getOptionValue());
            }
        }
        int writeSize = writeList.size();
        int standandSize = standardAnswerList.size();

        if (buttonStatus != JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_SEE_ANSWER) {
            if (writeSize != standandSize) {
                buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_GRAY;
            } else {
                buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_LIGHT;
            }
        }

        Utils.notifyButtonBg(buttonStatus, commitImage);
    }


    private void judgeRightOrWrong() {

        if (Utils.compare(writeList, standardAnswerList)) {
            RIGHT_NUM++;
            state = 1;
            CartoonToastUtils.show(true);
        } else {
            state = 0;
            CartoonToastUtils.show(false);
        }
    }

    /**
     * 填充
     */
    class FillBlankAdapter extends TagAdapter<CartoonFillBlankBean> {

        public FillBlankAdapter(List<CartoonFillBlankBean> datas) {
            super(datas);
        }

        @Override
        public View getView(FlowLayout parent, int position, CartoonFillBlankBean cartoonFillBlankBean) {
            LinearLayout view = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.sentence_question_name_layout, flowLayout, false);
            final TextView question = (TextView) view.findViewById(R.id.question_letter);


            if ("##".equals(cartoonFillBlankBean.getValue())) {

                switch (cartoonFillBlankBean.getStatus()) {
                    case STATUS_DEFAULT:

                        /**---将隐藏的选项显示出来------**/
                        for (int i = 0; i < optionsTextList.size(); i++) {
                            if (String.valueOf(optionsTextList.get(i).getId()).equals(cartoonFillBlankBean.getId())) {
                                optionsTextList.get(i).setHidden(0);
                                optionsTextList.get(i).setStatus(null);
                                cartoonFillBlankBean.setOptionValue("");
                                cartoonFillBlankBean.setId("");

                            }
                        }
                        if (adapter != null) {
                            isShowCommit();
                            adapter.notifyDataSetChanged();
                        }
                        question.setText("");
                        question.setBackgroundResource(R.mipmap.cartoon_sentence_transparent_doted);
                        break;
                    case STATUS_CHOOSE:
                        question.setText("");
                        question.setBackgroundResource(R.mipmap.cartoon_sentence_white_dotted);
                        break;
                    case STATUS_WORD:
                        if (!TextUtils.isEmpty(cartoonFillBlankBean.getOptionValue())) {
                            question.setText(cartoonFillBlankBean.getOptionValue());
                        }
                        /**---隐藏选项------**/
                        for (int i = 0; i < optionsTextList.size(); i++) {
                            if (String.valueOf(optionsTextList.get(i).getId()).equals(cartoonFillBlankBean.getId())) {
                                optionsTextList.get(i).setHidden(1);
//                                optionsTextList.get(i).setValue("");
                            }
                        }

                        if (adapter != null) {
                            isShowCommit();
                            adapter.notifyDataSetChanged();
                        }

                        question.setBackgroundResource(R.mipmap.cartoon_sentence_white_dotted);
                        break;

                    case STATUS_WRONG:
                        if (!TextUtils.isEmpty(cartoonFillBlankBean.getOptionValue())) {
                            question.setText(cartoonFillBlankBean.getOptionValue());
                            question.setBackgroundResource(R.mipmap.cartoon_word_long_wrong);
                        }
                        break;

                    case STATUS_RIGHT:
                        if (!TextUtils.isEmpty(cartoonFillBlankBean.getOptionValue())) {
                            question.setText(cartoonFillBlankBean.getOptionValue());
                            question.setBackgroundResource(R.mipmap.cartoon_word_long_right);
                        }
                        break;
                }

            } else {
                question.setText(cartoonFillBlankBean.getValue());
                question.setBackground(null);
            }


            return view;
        }
    }

    private void jumpToFragment(final int index) {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                FragmentManager manager = getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                returnToOriginal();
                Utils.switchFragment(getActivity(), transaction, questionList, index, R.id.fg_container, type,
                        homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
            }
        }, 1500);
    }


    private void commitAnswers() {
        commitAnswerBeanList = new ArrayList<>();
        for (CartoonFillBlankBean textsBean : blankList) {
            if (!TextUtils.isEmpty(textsBean.getOptionValue())) {
                CartoonCommitAnswerBean bean = new CartoonCommitAnswerBean();
                bean.setResourceType("0");
                bean.setQuestionResourceId(textsBean.getId());
                writeAnswerIdList.add(textsBean.getId());
                commitAnswerBeanList.add(bean);
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("classId", MyApplication.classIDStr);
        map.put("state", state);
        map.put("homeworkPackageId", homePackageId);
        map.put("objectQuestionId", questionVOsBean.getQuestionId());
        map.put("answerResourceList", commitAnswerBeanList);
        map.put("studentHomeworkId", studentHomeworkId);
        HttpMehtod.getInstance().cartoonCommitHomeAnsers(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                switch (type) {
                    case NOT_CORRECTED:
                    case HAS_CORRECTED:
                    case ERROR_KINDS:
                        if (state == 1) {
                            jumpToFragment(currentIndex + 1);
                        } else {
                            errorLogicBusiness();
                        }
                        break;

                    case DO_WORK:
                    case CONTINUE_WORK:
                    case DO_IT_AGAIN:
                        jumpToFragment(currentIndex + 1);
                        break;
                }
            }
        });

    }

    private void errorLogicBusiness() {
        returnToOriginal();
        List<String> tempStrList = new ArrayList<>();
        List<CartoonFillBlankBean> blankBeanList = new ArrayList<>();
        for (int i = 0; i < optionsTextList.size(); i++) {
            if (writeAnswerIdList.size() > 0 && String.valueOf(optionsTextList.get(i).getId()).equals(writeAnswerIdList.get(0))) {
                CartoonFillBlankBean blankBean = new CartoonFillBlankBean();
                String value = optionsTextList.get(i).getValue();
                tempStrList.add(value);
                blankBean.setValue(value);
                blankBean.setId(String.valueOf(optionsTextList.get(i).getId()));
                blankBeanList.add(blankBean);

                optionsTextList.get(i).setHidden(1);
                writeAnswerIdList.remove(0);
            }
        }

        List<String> tempAnswerList = new ArrayList<>();
        tempAnswerList.addAll(standardAnswerList);
        int index = 0; //标志顺序
        for (int i = 0; i < blankList.size(); i++) {

            if ("##".equals(blankList.get(i).getValue())) {
                if (blankBeanList != null && blankBeanList.size() > 0 && tempAnswerList != null && tempAnswerList.size() > 0) {
                    if (blankBeanList.get(0).getValue().equals(tempAnswerList.get(0))) {
                        blankList.get(i).setStatus(STATUS_RIGHT);
                    } else {
                        blankList.get(i).setStatus(STATUS_WRONG);
                    }
                    tempAnswerList.remove(0);
                    blankList.get(i).setIndex(index);
                    blankList.get(i).setId(blankBeanList.get(0).getId());
                    blankList.get(i).setOptionValue(tempStrList.get(0));
                    blankBeanList.remove(0);
                    index++;
                }

            }
        }


        commitImage.setVisibility(View.VISIBLE);
        buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_SEE_ANSWER;
        Utils.notifyButtonBg(buttonStatus, commitImage);

        fillBlankAdapter.notifyDataChanged();
        adapter.notifyDataSetChanged();

    }


    private void errorQuestionCommitAnswer() {

        Map<String, Object> map = new HashMap<>();
        map.put("studentHomeworkDoneDetailId", questionVOsBean.getStudentHomeworkDoneDetailId());
        HttpMehtod.getInstance().cartoonCorrectErrorQuestion(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                jumpToFragment(currentIndex + 1);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.commit_image:
                switch (buttonStatus) {
                    case STATUS_LIGHT:
                        judgeRightOrWrong();
                        switch (type) {
                            case DO_WORK:
                            case CONTINUE_WORK:
                            case DO_IT_AGAIN:
                            case HAS_CORRECTED:
                                commitAnswers();
                                break;
                            case NOT_CORRECTED:
                            case ERROR_KINDS:
                                if (state == 1) {
                                    errorQuestionCommitAnswer();
                                } else {
                                    errorLogicBusiness();
                                }
                                break;
                        }
                        break;
                    case STATUS_SEE_ANSWER:
                        seeAnswer();
                        break;
                    case STATUS_ANALYSIS:
                        CartoonAnalysisPopu popu = new CartoonAnalysisPopu(getActivity(), analysisText, commitImage);
                        popu.showPopupWindow();
                        break;
                }

                break;

            case R.id.previous_question:
                returnToOriginal();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                Utils.switchFragment(getActivity(), transaction, questionList, currentIndex - 1, R.id.fg_container,
                        type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
            case R.id.next_question:
                returnToOriginal();
                FragmentTransaction transaction2 = getFragmentManager().beginTransaction();
                Utils.switchFragment(getActivity(), transaction2, questionList, currentIndex + 1, R.id.fg_container,
                        type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);

                break;
            case R.id.voice_image:
                Utils.playOrPauseAudio(audioPlayer, audioUrl, voiceImage);
                break;

        }
    }

    /**
     * 把questionList还原到初始状态
     */
    private void returnToOriginal() {

        for (CartoonTextsBean bean : optionsTextList) {
            bean.setHidden(0);
        }
    }

    /**
     * 查看答案
     */
    private void seeAnswer() {

        List<String> tempAnswerList = new ArrayList<>();
        tempAnswerList.addAll(standardAnswerList);

        int dex = 0;
        for (int i = 0; i < blankList.size(); i++) {

            LogUtil.MyLog("seeAnswer", blankList.get(i).getValue() + "====" + blankList.get(i).getStatus());
            /**---将错误的填空显示正确的选项， 并将原来错误的选择在选项中标注出来，还有将正确的选项隐藏～～～～--**/
            if ("##".equals(blankList.get(i).getValue())) {

//                for (int q = 0; q < standardAnswerList.size(); q++) {
//                    LogUtil.MyLog("tempAnswerList", standardAnswerList.get(q) + "====" + blankList.get(i).getStatus());
//                }

//                int index = blankList.get(i).getIndex();

                String errorValue = blankList.get(i).getOptionValue();
                String value = standardAnswerList.get(dex);
                dex++;
                blankList.get(i).setOptionValue(value);
                blankList.get(i).setStatus(STATUS_RIGHT);
                String id = "";

                for (int j = 0; j < optionsTextList.size(); j++) {
                    LogUtil.MyLog("blankList", j + "====" + blankList.get(i).getId() + "------" + optionsTextList.get(j).getId());

                    if (blankList.get(i).getId().equals(String.valueOf(optionsTextList.get(j).getId()))) {
                        optionsTextList.get(j).setValue(errorValue);
                        optionsTextList.get(j).setStatus(STATUS_WRONG);
                        optionsTextList.get(j).setHidden(0);
                        break;
                    }
                }

                for (CartoonTextsBean blankBean : optionsTextList) {

                    LogUtil.MyLog("blankList", blankBean.getValue() + "==optionsTextList==" + value + "------");
                    if (blankBean.getValue().equals(value)) {
                        id = String.valueOf(blankBean.getId());
                        break;
                    }
                }

                for (int k = 0; k < optionsTextList.size(); k++) {
                    if (id.equals(String.valueOf(optionsTextList.get(k).getId()))) {
                        optionsTextList.get(k).setHidden(1);
                        break;
                    }
                }
            }
        }

        adapter.notifyDataSetChanged();
        fillBlankAdapter.notifyDataChanged();
        buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_ANALYSIS;
        Utils.notifyButtonBg(buttonStatus, commitImage);


    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(int currentIndex, int totalNum, String title) {
        if (mListener != null) {
            mListener.onGrammarChooseFillBlank(currentIndex, totalNum, title);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnGrammarChooseFillBlankListener) {
            mListener = (OnGrammarChooseFillBlankListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnGrammarChooseFillBlankListener {
        // TODO: Update argument type and name
        void onGrammarChooseFillBlank(int currentIndex, int totalNum, String title);
    }
}
